<template>
    <el-upload class="avatar-uploader" action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
        :multiple="state.config.multiple" :show-file-list="false" :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="state.img" :src="state.img" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><ele-Plus /></el-icon>
    </el-upload>
</template>
<script setup lang="ts">
import { reactive } from "vue";
import { ElMessage, UploadProps } from 'element-plus';
import { Session } from "/@/utils/storage";
import axios from "axios";

const emit = defineEmits(['uploadSuccess']);

const props = defineProps({
    img: {
        type: String,
        default: () => ('')
    },
    multiple: {
        type: Boolean,
        default: () => (false)
    }
})
const state = reactive({
    img: props.img,
    config: {
        //图片类型限制
        imgType: ['image/jpeg', 'image/png', 'image/gif'],
        //图片大小限制，单位MB
        imgSize: 15,
        //是否多选文件上传
        multiple: props.multiple,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + Session.getToken() },
        // 上传的地址
        url: import.meta.env.VITE_API_URL + import.meta.env.VUE_APP_UPLOAD_URL
    }
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    state.img = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (!state.config.imgType.includes(rawFile.type)) {
        ElMessage.error('上传头像图片只能是 JPG 格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > state.config.imgSize) {
        ElMessage.error('图片大小不能超过 5MB!')
        return false
    }
    const formData = new FormData()
    formData.append('file', rawFile)
    axios.post(
        state.config.url,
        formData, 
        { headers: state.config.headers }
    ).then(res => {
        if (res.data.code == 200) {
            state.img = res.data.data.url
            emit('uploadSuccess', res.data.data.url)
        } else {
            ElMessage.error(res.data.msg)
        }
    })
    return true
}

</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>